package com.main;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.io.IOUtils;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import java.io.*;

public class Main extends Application {
    
    public static String FILE_NAME = "img";
    private static TextArea text;

    @Override
    public void stop() throws Exception {
        super.stop();
        System.exit(1);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Button btn = new Button();
        btn.setText("开始下载图片");

        text = new TextArea("下载日志\n");
        btn.setOnAction((e) -> {
            System.out.println("hello world。。。\n");
            try {
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        try {
                            startDown();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }.start();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });

        StackPane root = new StackPane();
        root.getChildren().add(text);
        root.getChildren().add(btn);

        //场景
        Scene scene = new Scene(root, 800, 650);
        primaryStage.setTitle("下载图片");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    public static void main(String[] args) throws Exception {
        launch(args);
    }

    public static void startDown() throws Exception {
        new File(FILE_NAME).mkdirs();
        OkHttpClient client = new OkHttpClient();
        int totalPage = 100;
        for(int i=1; i<=totalPage; i++) {
            String url = "https://www.walanwalan.com/designs/all/page"+i+"/";
            String res = sendGetRequest(client, url);
            downHtmlImg(res);
            text.appendText("\n*****************" + i);
        }
    }

    private static void test() throws Exception {

        String h = IOUtils.toString(new FileInputStream(new File("/Volumes/extend_data/project/AD/wl-test/src/main/resources/1.html")));
        HtmlCleaner htmlCleaner = new HtmlCleaner();
        TagNode tagNode = htmlCleaner.clean(h);

        Object aArr = tagNode.evaluateXPath("//div[@class='container']//div[@class='row row10']")[0];
        TagNode t = (TagNode)aArr;
        Object[] arr = t.evaluateXPath("//a[@class='design_grid_link']//img[@class='lazy img-responsive']");
        for(Object o: arr) {
            TagNode n = (TagNode) o;
            String img = n.getAttributeByName("data-original");
            System.out.println(img);
            downImg(img);
            break;
        }
    }

    private static void downHtmlImg(String html) throws Exception {
        HtmlCleaner htmlCleaner = new HtmlCleaner();
        TagNode tagNode = htmlCleaner.clean(html);

        Object aArr = tagNode.evaluateXPath("//div[@class='container']//div[@class='row row10']")[0];
        TagNode t = (TagNode)aArr;
        Object[] arr = t.evaluateXPath("//a[@class='design_grid_link']//img[@class='lazy img-responsive']");
        if(arr.length < 1) {
            throw new RuntimeException("downHtmlImg...");
        }
        for(Object o: arr) {
            TagNode n = (TagNode) o;
            String img = n.getAttributeByName("data-original");
            text.appendText(".");
            // https://www.walanwalan.com/wldata/cacheimgs/photos/1587324_son/ed56d37ad5c8c0d4f8ed6bd93bc1ba3e.jpg
            // https://www.walanwalan.com/design_1587324.jpg
            downImg(img);
            String bigImg = img.substring(0, img.indexOf("_"));
            bigImg = "https://www.walanwalan.com/design_" + bigImg.substring(bigImg.lastIndexOf("/")+1) + ".jpg";
            downImg(bigImg);
        }
        text.appendText("\n----\n");
    }

    private static void downImg(String url) {
        try {
            String fName = url.substring(url.lastIndexOf("/")+1);
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();
            InputStream is = response.body().byteStream();
            IOUtils.copy(is, new FileOutputStream(new File(FILE_NAME + "/"+fName)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String sendGetRequest(OkHttpClient client, String url) {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
